package com.laizt.client.util;

import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ShareFileUtils {
    /**
     * 下载文件到指定文件夹
     * @param remoteUrl
     * @param fileName
     * @param localDir
     */
    public static void downloadFileToFolder(String remoteUrl, String fileName, String localDir,Map<String,Object> resultMap) {
        InputStream in = null;
        OutputStream out = null;
        try {
            if(!(new File(localDir)).exists())new File(localDir).mkdirs();
            SmbFile remoteFile = new SmbFile(remoteUrl + File.separator + fileName);
            File localFile = new File(localDir + File.separator + fileName);

            in = new BufferedInputStream(new SmbFileInputStream(remoteFile));
            out = new BufferedOutputStream(new FileOutputStream(localFile));
            byte[] b = new byte[1024];
            int len=-1;
            while((len=in.read(b)) != -1){
                out.write(b,0,len);//增加起始长度 每次都写入实际读到的长度，所以不会出现空字符。
            }
        } catch (Exception e) {
            e.printStackTrace();
            if(e.getMessage().contains("另一个程序正在使用此文件")){
                resultMap.put("code","01");
                resultMap.put("msg","测试软件已经打开,请勿重复打开！");
                return;
            }
        } finally {
            try {
                if(out!=null)out.close();
                if(in!=null)in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static final Logger logger = LoggerFactory.getLogger(ShareFileUtils.class.getName());

    /**
     * 读取共享文件夹下的所有文件(文件夹)的名称
     */
    public static void getSharedFileList(Map<String,Object> resultMap,Map<String,Object> map,String remoteIp,int count) {
        count++;
        String remoteUrl = (String) map.get("remoteUrl");
        String localDir = (String) map.get("dir");
        String port = (String) map.get("port");
        SmbFile smbFile;
        try {
            // smb://userName:passWord@host/path/
            logger.info("====实际请求的共享url===="+remoteUrl);
            smbFile = new SmbFile(remoteUrl);
            if (!smbFile.exists()) {
                resultMap.put("code","01");
                resultMap.put("msg","共享目录【"+remoteUrl+"】不存在！");
                return;
            } else {
                SmbFile[] files = smbFile.listFiles();
                boolean  hasXml = false;
                //下载文件
                for (SmbFile f : files) {
                    try {
                        if(f.isDirectory()){
                            //如果是目录按找目录下载
                             downSecOnd( f, remoteUrl, f.getName(), localDir);
                             continue;
                        }else{
                            logger.info("=========="+f.getName());
                            if("D5_CONFIG.cnf".equals(f.getName())){
                                File localFile = new File(localDir + File.separator + f.getName());
                                if(localFile.exists()){
                                    logger.info("===已经存在D5_CONFIG.cnf文件==不重新拉去");
                                    continue;
                                }
                            }
                            if("cp3testprogram.exe".equals(f.getName())){
                                File localFile = new File(localDir + File.separator + f.getName());
                                if(localFile.exists()){
                                    continue;
                                }
                            }
                            downloadFileToFolder(remoteUrl,f.getName(),localDir, resultMap);
                            if("01".equals(resultMap.get("code")))return;
                            if(f.getName().contains("ConfigFile")){
                                //修改配置文件的服务器连接地址和端口
                                changeFileContent(localDir,"ConfigFile.xml",remoteIp+","+port+"");
                            }
                            if("cp3testprogram.exe".equals(f.getName())){
                                hasXml = true;
                            }
                        }
                    } catch (SmbException e) {
                        e.printStackTrace();
                    }
                }
                if(!hasXml){
                    resultMap.put("code","01");
                    resultMap.put("msg","共享目录中未下载到可用的测试软件！");
                    return;
                }
            }
        } catch (Exception e) {
            resultMap.put("code","01");
            resultMap.put("msg","请求共享目录【"+remoteUrl+"】失败！");
            logger.info("==错误信息="+e.getMessage());
            if(e.getMessage()!=null&&e.getMessage().contains("Logon failure")){
               /* if(count<2){
                    logger.info("====账号或密码不正确，使用无账号密码重试一次:"+map.get("nopwdurl")+"第"+count+"次");
                    resultMap.put("code","00");
                    resultMap.put("msg","打开测试软件成功！");
                    map.put("remoteUrl",map.get("nopwdurl"));
                    getSharedFileList(resultMap,map, remoteIp,count);
                    System.out.println(resultMap+"================");
                }else{*/
                    resultMap.put("code","01");
                    resultMap.put("msg","登录的账号或密码不正确！");
               /* }*/
            }else{
                e.printStackTrace();
            }
        }
    }

    public static void checkVersionIsSame(Map<String,Object> resultMap,Map<String,Object> map,String remoteIp,int count) {
        count++;
        String remoteUrl = (String) map.get("remoteUrl");
        String localDir = (String) map.get("dir");
        String port = (String) map.get("port");
        SmbFile smbFile;
        try {
            // smb://userName:passWord@host/path/
            logger.info("====实际请求的共享url===="+remoteUrl);
            smbFile = new SmbFile(remoteUrl);
            if (!smbFile.exists()) {
                resultMap.put("code","01");
                resultMap.put("msg","共享目录【"+remoteUrl+"】不存在！");
                return;
            } else {
                SmbFile[] files = smbFile.listFiles();
                boolean  hasXml = false;
                //下载文件
                for (SmbFile f : files) {
                    try {
                        if(f.isDirectory()){
                            //如果是目录按找目录下载
                            downSecOnd( f, remoteUrl, f.getName(), localDir);
                            continue;
                        }else{
                            logger.info("=========="+f.getName());
                            if("D5_CONFIG.cnf".equals(f.getName())){
                                File localFile = new File(localDir + File.separator + f.getName());
                                if(localFile.exists()){
                                    logger.info("===已经存在D5_CONFIG.cnf文件==不重新拉去");
                                    continue;
                                }
                            }
                            downloadFileToFolder(remoteUrl,f.getName(),localDir, resultMap);
                            if("01".equals(resultMap.get("code")))return;
                            if(f.getName().contains("ConfigFile")){
                                //修改配置文件的服务器连接地址和端口
                                changeFileContent(localDir,"ConfigFile.xml",remoteIp+","+port+"");
                            }
                            if("cp3testprogram.exe".equals(f.getName())){
                                hasXml = true;
                            }
                        }
                    } catch (SmbException e) {
                        e.printStackTrace();
                    }
                }
                if(!hasXml){
                    resultMap.put("code","01");
                    resultMap.put("msg","共享目录中未下载到可用的测试软件！");
                    return;
                }
            }
        } catch (Exception e) {
            resultMap.put("code","01");
            resultMap.put("msg","请求共享目录【"+remoteUrl+"】失败！");
            logger.info("==错误信息="+e.getMessage());
            if(e.getMessage()!=null&&e.getMessage().contains("Logon failure")){
                resultMap.put("code","01");
                resultMap.put("msg","登录的账号或密码不正确！");
                /* }*/
            }else{
                e.printStackTrace();
            }
        }
    }





    public static void downSecOnd(SmbFile smbFile,String remoteUrl,String dirName,String localDir){
        SmbFile[] files2 = null;
        try {
             files2 = smbFile.listFiles();
        } catch (SmbException e) {
            e.printStackTrace();
        }
        for (SmbFile f : files2) {
            try {
                if(f.isDirectory()){
                    //如果是目录按找目录下载
                    continue;
                }else{
                    downloadFileToFolder(remoteUrl+"/"+dirName,f.getName(),localDir+"/"+dirName, null);
                }
            } catch (SmbException e) {
                e.printStackTrace();
            }
        }

    }




    /**
     * 修改ConfigFile.xml文件内容中连接服务器的Ip和端口
     */
    public static void changeFileContent(String localDir,String fileName,String replaceContent){
        String filePath = localDir + File.separator + fileName;
        //读取文件
        String content = readFile(filePath, replaceContent);
        writeFile(filePath, content);
    }

    private static String readFile(String filePath, String replaceContent){
        String cmd = "<IMS_ServerPort>";
        BufferedReader br = null;
        String line;
        StringBuffer bufAll = new StringBuffer();
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),"UTF-8"));
            while ((line = br.readLine()) != null) {
                Map<String, Pattern> map = new HashMap<>();
                String reg = "(\\<IMS_ServerPort>.+?\\</IMS_ServerPort>)";
                Pattern patter = Pattern.compile(reg, Pattern.DOTALL | Pattern.MULTILINE);
                map.put("IMS_ServerPort", patter);
                java.util.regex.Matcher match = map.get("IMS_ServerPort").matcher(line);
                if (match.find()) {
                    line = match.replaceAll("<IMS_ServerPort>"+replaceContent+"</IMS_ServerPort>");
                }
                bufAll.append(line);
                bufAll.append(System.getProperty("line.separator"));
            }
            bufAll.deleteCharAt(bufAll.length()-1);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (br != null) {
                try {
                    br.close();
                }catch (IOException e){
                    br = null;
                }
            }
        }
        //logger.info("修改后配置文件内容："+bufAll.toString());
        return bufAll.toString();

    }

    private static void writeFile(String filePath, String content) {
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath),"UTF-8"));
            bw.write(content);
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (bw != null){
                try{
                    bw.close();
                }catch (IOException e) {
                    bw = null;
                }
            }
        }
    }

    public static void dealUrl(Map<String,Object> map){
        //map.put("remoteUrl","smb://cmes:semc@192.168.7.253/Routeway/TEST/6A-III-AV3/");
        String dir = (String)map.get("dir");
        String remoteUrl = (String)map.get("remoteUrl");
        String user =(String)map.get("user");
        String pwd =(String)map.get("pwd");
        String remoteIp = (String)map.get("remoteIp");
        //检测字符串是否有ip。如果有ip,在Ip处进行截取
        if(checkIpPosition(map)){
            remoteUrl = (String)map.get("remoteUrl");
            remoteIp = (String)map.get("remoteIp");
        }
        StringBuilder sb = new StringBuilder();
        sb.append("smb://"+user+":"+pwd+"@"+remoteIp+"");

        StringBuilder sbnopwd = new StringBuilder();
        sbnopwd.append("smb://"+remoteIp+"");

        if(!"\\".equals(remoteUrl.substring(remoteUrl.length()-1))){
            remoteUrl+="\\";
        }
        if(remoteUrl.indexOf("\\")==0){
            dir = dir+remoteUrl;
            remoteUrl = remoteUrl.replaceAll("\\\\", "/");
            sb.append(remoteUrl);
            sbnopwd.append(remoteUrl);
        }else{
            dir = dir+"\\"+remoteUrl;
            remoteUrl = remoteUrl.replaceAll("\\\\", "/");
            sb.append("/" + remoteUrl);
            sbnopwd.append("/" + remoteUrl);
        }
        logger.info("当前将要保存的文件路径:"+dir);
        logger.info("当前将要请求的共享URL:"+sb.toString());
        map.put("dir",dir);
        map.put("remoteUrl",sb.toString());
        map.put("nopwdurl",sbnopwd.toString());
    }

    public static boolean  checkIpPosition(Map<String,Object> map){
        boolean hasIp = false;
        String remoteUrl = (String)map.get("remoteUrl");
        String regexString="\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
        Pattern p = Pattern.compile(regexString);
        Matcher m = p.matcher(remoteUrl);
        boolean result = m.find();
        String ip = "";
        while(result) {
            ip = m.group();
            result = m.find();
        }
        //有ip则需要分割处理
        if(!"".equals(ip)){
            String realDir = remoteUrl.substring(remoteUrl.indexOf(ip)+ip.length());
            map.put("remoteIp",ip);
            map.put("remoteUrl",realDir);
            hasIp = true;
        }
        return hasIp;
    }
    public static void main(String[] args) {
        //dealUrl(null);
        checkIpPosition(null);
    }
}
